package org.yaukie.auth.handler;

import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.io.Serializable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.yaukie.auth.constant.AjaxResult;
import org.yaukie.base.util.MessageTools;
import org.yaukie.base.util.ServletUtils;
import org.yaukie.base.util.StringTools;

@Component
public class UnAuthorizationHandler implements Serializable, AuthenticationEntryPoint {
    private static final Logger log = LoggerFactory.getLogger(UnAuthorizationHandler.class);

    public UnAuthorizationHandler() {
    }

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        if (log.isInfoEnabled()) {
            log.info("系统模块{}执行授权校验....", this.getClass().getSimpleName());
        }

        int code = 401;
        String msg = MessageTools.message("yaukie.user.unauthorized.error", new Object[0]);
        msg = StringTools.format(msg, new Object[]{request.getRequestURL()});
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
    }
}
